const Parser = require('./parser');
const parser = new Parser();
const readline = require('readline');
const fs = require('fs');

// 分析日志,获取 gc 信息字符串.
class GC {
	constructor(props) {
		// nvp 信息
		this.nvp = ''
		// gc 相信信息
		this.verbose = []
		// 一条有效信息开始
		this.begin = undefined
		// 行游标
		this.cursor = 0
		// 有效数据行数,默认9行
		this.verboseLines = 9
		// 存储 gc 数据
		this.gcList = []
		// log 日志位置
		this.pm2File = props.pm2

		this.task = null
	}
	getGc(cb) {
		const me = this
		this.gcList = []
		const rl = readline.createInterface({
  			input: fs.createReadStream(this.pm2File)
		});


		rl.on('line', (line) => {
			if(line.indexOf('pause=') != -1 && line.indexOf('total_size_after=') !=-1) {
				// 一条 gc 开始
				me.setPros(true)
			}
			if(me.begin) {
				// 读取第一行有效数据
				if(me.cursor === 0) {
					me.nvp = line
					me.cursor++
				}else if(me.cursor < me.verboseLines) {
					// 有效数据读取中...
					me.verbose.push(line)
					me.cursor++
				}else{
					me.verbose.push(line)
					// 一条 gc 数据读取完毕.
					let nvp = parser.parseAllToData(me.nvp + '\n')[0]
					let nvpData = nvp && nvp.data
					let verbose = parser.parseAllToData(me.verbose.join('\n'))[0]

					me.gcList.push(Object.assign({},verbose,nvpData && {
						// 一次 gc 掉内存
						reduce_memory: nvpData.reduce_memory,
						// 对象存活比例
						average_survival_ratio: nvpData.average_survival_ratio,
						// gc type
						gc: nvpData.gc,
						// 新拷贝到新空间的对象数量
						nodes_copied_in_new: nvpData.nodes_copied_in_new,
						// 新空间要杀掉对象个数
						nodes_died_in_new: nvpData.nodes_died_in_new,
						// gc 时间间隔
						mutator: nvpData.mutator
					}))
					// 重置属性.便于下次有效数据读取
					me.setPros()
				}
			}
		})
		.on('close', () => {
			fs.writeFileSync(me.pm2File,'')
			typeof cb === 'function' && cb(me.gcList)
			
		})
		return this;
	}
	setPros(isBegin) {
		this.nvp = ''
		this.verbose = []
		this.begin = isBegin
		this.cursor = 0
	}
}

module.exports = GC